<?php
/**
 * 总后台控制器
 *
 * @package    app
 * @version    1.0
 * @author     Ray 33705910@qq.com
 * @license    MIT License
 * @copyright  2013 - 2015 Ray
 * @link       http://wangxiaolei.cn
 */

/**
 * 本控制器主要用于：
 * 1.
 * @package  app
 * @extends  Controller
 */
namespace mobile;

class Controller_Home extends \Controller_BaseController{

    public $template = "template";

	public function before(){

        parent::before();
		
        $params = array(
            'controller_name' => '网站'
        );
        
        \View::set_global($params);
    }

	public function action_index() {
	        \Response::redirect("/mobile/index");
	}

	//填写个人资料
	public function action_profile() {
        $params = array(
            'title' => '填写信息',
            'menu' => 'mobile',
            'error' => '',
            'index_title' => '个人信息 >> 填写信息',
            'baseUrl' => \Uri::base()
        );
        
         if(\Input::method() == "POST"){
         	$config = \Config::load('website.php', true);
			$target_path = $config['upload_file_path'];
			$photoalbum = [];

			
			$data = \Input::post();			
			//校验,查身份证不允许重复
			$people = \Model_People::query()->where(array("identity"=>$data['identity']))->get_one();
			if(!empty($people))
			{ //检测是否登陆了，登陆了表示编辑，非登陆状态表示 此信息已提交过，请登录后再修改				
				if(isset($people) && $people && $people->last_name ==$data['reqName']){					//修改					
					if(isset($data['photoalbum']))
					{
						foreach ( json_decode($data['photoalbum']) as $key => $value) {
							array_push($photoalbum, array('people_id'=>$people->user_id,'src' => $target_path.$value,'file_name' => $value));
						}						
					}
	                $result = $people->do_update($people->user_id,array('email' => $data['reqEmail'],'last_name' =>$data['reqName']
	                	,'phone' =>$data['reqPhone']
	                	,'gender'=>$data['reqSex'],'address'=>$data['reqAddress'],'residence_address'=>$data['residenceAddress']
	                	,'introduction' => $data['reqContent'],'birthday' => $data['reqBirthday'],'photoalbum' => $photoalbum));
	                //$result = $people->save();

	                return json_encode(array('status' => 'success', 'msg'=>'修改成功！'));
	                //$url = '/mobile/ucenter/index?msg='.urlencode('修改成功！');
				}else{
					//身份证号码已注册,请直接登陆。
					//$url = '/mobile/home/login?msg='.urlencode('请登录后再修改！');
	                return json_encode(array('status' => 'error', 'msg'=>'请登录后再修改！'));
				}

				//\Response::redirect($url);
			}

			//检测手机号码是否注册过
			$user = \Model\Auth_User::query()->where(array('username' => $data['reqPhone']))->get_one();

			if($user){
				$errTitle = urlencode("系统错误");
		        $errContent = urlencode("系统错误，手机号码已被占用!");
		        //\Response::redirect("/moobile/page/error?errTitle".$errTitle."&errContent=".$errContent);
	            return json_encode(array('status' => 'error', 'msg'=>$errContent));
			}

			$user =\Model\Auth_User::query()->where(array('email' => $data['reqEmail']))->get_one();
			if($user){
				$errTitle = urlencode("系统错误");
		        $errContent = urlencode("系统错误，邮箱已被占用...");
		        //\Response::redirect("/mobile/page/error?errTitle".$errTitle."&errContent=".$errContent);
		        return json_encode(array('status' => 'error', 'msg'=>$errContent));
			}
			/*
			if(! \Security::check_token()){
				$errTitle = urlencode("系统错误");
		        $errContent = urlencode("过期或无效的请求,建议刷新页面重试!");
		        //\Response::redirect("/mobile/page/error?errTitle".$errTitle."&errContent=".$errContent);
		        return json_encode(array('status' => 'error', 'msg'=>$errContent));
            }*/

			$flag = \Auth::create_user($data['reqPhone'], '5201314', $data['reqEmail'], 7);

			//$user->password = \Auth::instance()->hash_password($data['password']);
			$config = \Config::load('website.php', true);
			$target_path = $config['upload_file_path'];
			$photoalbum = [];
			if(isset($data['photoalbum']))
			{
				foreach ( json_decode($data['photoalbum']) as $key => $value) {
					array_push($photoalbum, array('people_id'=>$flag,'src' => $target_path.$value,'file_name' => $value));
				}						
			}
			$people = \Model_People::forge();
			
			$people->do_create(array('user_id' => $flag,'email' => $data['reqEmail']
				,'last_name' =>$data['reqName'],'identity'  =>$data['identity']
				,'phone' =>$data['reqPhone'],'gender'=>$data['reqSex'],'address'=>$data['reqAddress']
				,'residence_address'=>$data['residenceAddress'],'introduction' => $data['reqContent']
				,'birthday' => $data['reqBirthday'],'photoalbum' => $photoalbum));
			
			if($flag){						        
				//\Response::redirect('/mobile/home/login?msg=注册成功，请登录！');
				return json_encode(array('status' => 'success', 'msg'=>'保存成功！'));
			}else{
				//\Response::redirect('/mobile/reg/index');
				return json_encode(array('status' => 'error', 'msg'=>'服务器错误，保存失败！'));
			}

			$errTitle = urlencode("系统错误");
	        $errContent = urlencode("服务器无响应...");
	       \Response::redirect("/moobile/page/error?errTitle".$errTitle."&errContent=".$errContent);
			return json_encode(array('status' => 'error', 'msg'=>$errContent));
		}

		\View::set_global($params);
        $this->template->content = \View::forge("home/profile");
	}


	//留言
	public function action_contact() {
        if(\Input::is_ajax()){
        	$data = \Input::post();
        	if(!$data['code']){
        		die(json_encode(array('status' => 'error', 'msg' => ' 参数错误！', 'errcode' => 10)));
        	}

        	$lmData = array('name' => $data['name'], 'email' => $data['email'], 'content' => $data['content']);

        	$lm = \Model_LeaveMessage::forge($lmData);

            $ynSucc = $lm->save();

            if($ynSucc){
            	die(json_encode(array('status' => 'succ', 'msg' => ' 操作成功！', 'errcode' => 0)));
            }

        	die(json_encode(array('status' => 'error', 'msg' => ' 参数错误！', 'errcode' => 10)));
        }


        $errTitle = urlencode("系统错误！");
        $errContent = urlencode("找不到页面...");
        \Response::redirect("/web/page/error?errTitle".$errTitle."&errContent=".$errContent);
	}

	//忘记密码
	public function action_forget() {
		$params = array(
			'title' => '忘记密码?'
		);
		
		if(\Input::is_ajax()){
			$data = \Input::post();			
			if($data['setp'] == 1){
				//验证码+用户名
				session_start();
				if(!(isset($data['code']) && $data['code'])){
					die(json_encode(array('status' => 'error', 'msg' => ' 验证码错误！', 'errcode' => 10)));
				}

				if($_SESSION["vcode"] != $data['code']){
					die(json_encode(array('status' => 'error', 'msg' => ' 验证码错误！', 'errcode' => 10)));
				}

				if(!(isset ($data['username']) && $data['username']) || strlen($data['username'])<=0){
					die(json_encode(array('status' => 'error', 'msg' => ' 参数错误！', 'errcode' => 10)));
				}

				$user = \Model\Auth_User::query()->where(array('username' => $data['username']))->get_one();
				if($user){
					if($user->group_id == 6 || $user->group_id == 2){
						die(json_encode(array('status' => 'error', 'msg' => ' 系统错误！', 'errcode' => 10)));
					}

					if($user->group_id != 7){
						die(json_encode(array('status' => 'error', 'msg' => ' 参数错误，用户名不存在！', 'errcode' => 10)));
					}

					die(json_encode(array('status' => 'succ', 'msg' => 'ok', 'errcode' => 0, 'data' => array('username' => $user->username, 'email' => $user->email))));
				}
			}else if($data['setp'] == 2){
				//用户名
				session_start();
				if(!(isset($data['code']) && $data['code'])){
					die(json_encode(array('status' => 'error', 'msg' => ' 验证码错误！', 'errcode' => 10)));
				}

				if($_SESSION["vcode"] != $data['code']){
					die(json_encode(array('status' => 'error', 'msg' => ' 验证码错误！', 'errcode' => 10)));
				}

				if(!(isset ($data['username']) && $data['username']) || strlen($data['username'])<=0){
					die(json_encode(array('status' => 'error', 'msg' => ' 参数错误！', 'errcode' => 10)));
				}

				$user = \Model\Auth_User::query()->where(array('username' => $data['username']))->get_one();
				if($user){
					if($user->group_id == 6 || $user->group_id == 2){
						die(json_encode(array('status' => 'error', 'msg' => ' 系统错误！', 'errcode' => 10)));
					}

					if($user->group_id != 7){
						die(json_encode(array('status' => 'error', 'msg' => ' 参数错误，用户名不存在！', 'errcode' => 10)));
					}

					die(json_encode(array('status' => 'succ', 'msg' => 'ok', 'errcode' => 0, 'data' => array('username' => $user->username))));
				}
			}else if($data['setp'] == 3){
				if(!(isset ($data['username']) && $data['username']) || strlen($data['username'])<=0){
					die(json_encode(array('status' => 'error', 'msg' => ' 参数错误！', 'errcode' => 10)));
				}

				$user = \Model\Auth_User::query()->where(array('username' => $data['username']))->get_one();
				if($user){
					if($user->group_id == 6 || $user->group_id == 2){
						die(json_encode(array('status' => 'error', 'msg' => ' 系统错误！', 'errcode' => 10)));
					}

					if($user->group_id != 7){
						die(json_encode(array('status' => 'error', 'msg' => ' 参数错误，用户名不存在！', 'errcode' => 10)));
					}

					//修改密码
					$msg = '';
					if(! isset($data['newpwd']) || ! $data['surpwd']){
						$msg = '新密码不能为空';
					}

					if($msg){
						die(json_encode(array('status' => 'err', 'msg' => $msg, 'errcode' => 10)));
					}

					\Auth::force_login($user->id);

					$user->password = \Auth::instance()->hash_password($data['newpwd']);

					if($user->save()){
						die(json_encode(array('status' => 'succ', 'msg' => '修改密码成功', 'errcode' => 0)));
					}
					die(json_encode(array('status' => 'err', 'msg' => '原密码错误', 'errcode' => 20)));
				}
			}else{
				die(json_encode(array('status' => 'error', 'msg' => '参数错误！', 'errcode' => 10)));
			}

			die(json_encode(array('status' => 'error', 'msg' => ' 参数错误！', 'errcode' => 10)));
		}

		\View::set_global($params);
        $this->template->content = \View::forge("forget");
	}

	public function action_login(){
		\Auth::logout();
		\Session::destroy();
		if(\Input::get("msg",false)){
			\Session::set_flash('msg', array('status' => 'succ', 'msg' => '注册成功！', 'errcode' => 0));
		}
		
		$params = array(
        	'title' => '登录系统',
		);

		if(\Input::method() == 'POST'){
			$data = \Input::post();
			if(\Auth::login()){
				if (\Input::param('remember', false))
	            {
	                \Auth::remember_me(\Auth::get_user()->id);// create the remember-me cookie
	            } else {
	                \Auth::dont_remember_me(\Auth::get_user()->id);// delete the remember-me cookie if present
	            }

				if(isset(\Auth::get_user()->expire_at) && time() > \Auth::get_user()->expire_at){
					\Auth::logout();
			        $errTitle = urlencode("系统错误");
			        $errContent = urlencode("系统错误，帐户已过期...");
			        \Response::redirect("/web/page/error?errTitle".$errTitle."&errContent=".$errContent);
				}
				
				//初始化当前登录帐户扩展信息
				$people = \Model_People::query()
						->where('user_id', \Auth::get_user()->id)
						->get_one();
				\Session::set('current_people', $people);

				$redirect = "/web/index";
				if(isset($data['to_url'])){
					$redirect = $data['to_url'];
				}

				\Response::redirect($redirect);
				return;
			}

			\Session::set_flash('msg', array('status' => 'err', 'msg' => '登录失败，密码或用户名错误', 'errcode' => 20));
		}

		\View::set_global($params);
        $this->template->content = \View::forge("login");
	}

	public function action_change(){

		$params = array(
			'title' => '修改密码'
		);
		if(\Input::method() == 'POST'){

			$data = \Input::post();

			$msg = '';
			if(! isset($data['newPwd']) || ! $data['newPwd']){
				$msg = '新密码不能为空';
			}else if($data['newPwd'] == $data['oldPwd']){
				$msg = '新密码不能与原密码一样';
			}

			if( ! \Auth::check()){
				$msg = '请先登录';
			}

			if($msg){
				if(\Input::is_ajax()){
					die(json_encode(array('status' => 'err', 'msg' => $msg, 'errcode' => 10)));					
				}
			}

			if(\Auth::change_password($data['oldPwd'], $data['newPwd'])){
				if(\Input::is_ajax()){
					die(json_encode(array('status' => 'succ', 'msg' => '修改密码成功', 'errcode' => 0)));
				}
				\Session::set_flash('msg', array('status' => 'err', 'msg' => $msg, 'errcode' => 20));
				die(json_encode(array('status' => 'succ', 'msg' => '修改密码成功', 'errcode' => 0)));
			}
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '原密码错误', 'errcode' => 20)));
			}
			$errTitle = urlencode("系统错误");
	        $errContent = urlencode("系统错误，原密码错误...");
	        \Response::redirect("/web/page/error?errTitle".$errTitle."&errContent=".$errContent);
		}
	}

	public function action_logout(){
		\Auth::logout();
		\Session::destroy();
		\Response::redirect('/web/index');
	}

	public function action_404(){
		$params = array(
			'title' => '页面未找到',
			'action_name' => '页面未找到'
		);

		\View::set_global($params);
		return \Response::forge(\View::forge('error/404'));
	}

	public function action_500(){
		$params = array(
			'title' => '服务器内部错误',
			'action_name' => '服务器内部错误'
		);

		\View::set_global($params);
		return \Response::forge(\View::forge('error/500'));
	}

	public function action_error(){
		$params = array(
			'title' => '系统无法完成操作',
			'action_name' => '系统无法完成操作'
		);

		\View::set_global($params);
		return \Response::forge(\View::forge('error/error_msg'));
	}

	/**
	* 创建登录资料及会员资料
	*/
	private function create_user($data, $member = array()){
		$result = \Model_User::do_create($data);
    	if($result['status'] == 'succ'){
    		$base = array(
				'no' => time(),
				'status' => 'NONE',
				'reg_from' => 'qq'
			);			    		
    		\Session::set_flash('msg', array('status' => 'succ', 'msg' => '注册成功', 'errcode' => 0));
    	} else {
    		\Session::set_flash('msg', array('status' => 'err', 'msg' => $result['msg'], 'errcode' => 20));
    	}
    	return $result;
	}
}